package net.googlecode.kharchenko.dao.impl;

import net.googlecode.kharchenko.dao.PersonDAO;
import net.googlecode.kharchenko.domains.Group;
import net.googlecode.kharchenko.domains.Person;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Realization of PersonDAO.
 */
@Repository
public class PersonDAOImpl implements PersonDAO {

    /**
     * Entity manager for database access.
     */
    private EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {

        this.entityManager = entityManager;
    }


    public void savePerson(Person prs) {
        entityManager.merge(prs);

    }


    public Person getPerson(String email) {

        return (Person) entityManager.createQuery("from Person where email=?")
                .setParameter(1, email).getSingleResult();


    }


    public List<Person> getGroupMates(Person prs) {


        return (List<Person>) entityManager.createQuery("from Person where group=? and email != ?")
                .setParameter(1, prs.getGroup())
                .setParameter(2, prs.getEmail()).getResultList();

    }


    public List<Person> getTop5() {

        return (List<Person>) entityManager.createQuery("from Person order by rate desc ")
                .setFirstResult(0).setMaxResults(5).getResultList();

    }


    public Person getPersonById(Long id) {


        return (Person) entityManager.createQuery("from Person where id=?")
                .setParameter(1, id).getSingleResult();


    }


    public void giveVote(Long id, Person prs) {

        Person person = entityManager.find(Person.class, id);
        prs = entityManager.find(Person.class, prs.getId());
        person.setRate(person.getRate() + 1);
        person.getVotes().add(prs);

    }


    public void takeAwayVote(Long id, Person prs) {

        Person person = entityManager.find(Person.class, id);
        person.setRate(person.getRate() - 1);
        person.getVotes().remove(prs);

    }


    public boolean isVoteGiven(Long id, Person prs) {

        Person person = (Person) entityManager.find(Person.class, id);
        if (person.getVotes().contains(prs)) {
            return true;
        }

        return false;


    }


    public void updatePersonInfo(String email, Person prs) {

        Person person = getPerson(email);
        person.setFname(prs.getFname());
        person.setSname(prs.getSname());
        person.setTname(prs.getTname());
        person.setGroup(entityManager.find(Group.class, prs.getGroup().getId()));
        person.setImgurl(prs.getImgurl());
    }

    public void changePassword(String email, String newPass) {
        Person prs = getPerson(email);
        prs.setPassword(newPass);

    }


}
